let express = require('express');
let router = express.Router();

let redis = require("redis");
//     client = redis.createClient(32770, "www.c9200.xyz");

const d2100y = new Date('2100-01-01T00:00:00Z'); // 为了生成倒数时间戳

// var redis = require('redis'),
//     RDS_PORT = 6379,     //端口号
//     RDS_HOST = 'ung2018.pogorockgames.com',     //服务器IP
//     RDS_PWD = '1q2w3e4r5t',      //密码
//     RDS_OPTS = { auth_pass: RDS_PWD },
//     client = redis.createClient(RDS_PORT, RDS_HOST, RDS_OPTS);

const redis_config = {
    host: 'ung2018.pogorockgames.com',
    port: '6379',
    password: '1q2w3e4r5t',
    number: 1,
}

const url = `redis://:${redis_config.password}@${redis_config.host}:${redis_config.port}/${redis_config.number}`

const client = redis.createClient({ 'url': url });

client.on('ready', function (res) {
    console.log('ready');
});

client.on('end', function (err) {
    console.log('end');
});

client.on('error', function (err) {
    console.log(err);
});

client.on('connect', function () {
    console.log('redis connect success!');
});

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', { title: 'Leaderboard Demo' });
});

router.post('/uploadScore', function (req, res) {
    console.log('uploadScore req2', req.body);
    let key = req.body.key;
    let uid = req.body.uid;
    let score = req.body.score;
    let nickname = req.body.nickname;
    let wxid = req.body.wxid ?? '';
    let avatar = req.body.avatar ?? '';

    let userkey = `user:${uid}`;
    let uinfo = {
        uid,
        score,
        nickname,
        wxid,
        avatar
    };
    client.hmset(userkey, uinfo, function (err, data) { // hash存储用户信息，下一次快速存取。 直接存的是uinfo,搞得跟存了个对象一样
        console.log('hmset complete', err, data);
    });

    let countdown = Math.floor((d2100y - new Date()) / 1000);
    let scoreWithCountdown = score * 1e10 + countdown;

    client.zadd([key, scoreWithCountdown, uid], function (err, data) {
        console.log('zadd complete', err, data);
        res.send('OK');
    });
});

router.post('/uploadFOScore', function (req, res) {
    console.log('uploadScore req2', req.body);
    let key = req.body.key;
    let uid = req.body.uid;
    let incScore = req.body.incScore;
    let nickname = req.body.nickname;
    let wxid = req.body.wxid ?? '';
    let avatar = req.body.avatar ?? '';

    let userkey = `user:${uid}`;

    client.hmget(userkey, 'score', function (err, data) { // hash存储用户信息，下一次快速存取。 直接存的是uinfo,搞得跟存了个对象一样
        console.log('hmset complete', err, data[0]);

        let uinfo = {
            uid,
            score: incScore,
            nickname,
            wxid,
            avatar
        };
        if (data[0] != null) {
            uinfo.score += Number(data[0]);
        }
        if (uinfo.score < 0) uinfo.score = 0;

        client.hmset(userkey, uinfo, function (err, data) { // hash存储用户信息，下一次快速存取。 直接存的是uinfo,搞得跟存了个对象一样
            console.log('hmset complete', err, data);
        });

        let countdown = Math.floor((d2100y - new Date()) / 1000);
        let scoreWithCountdown = uinfo.score * 1e10 + countdown;

        client.zadd([key, scoreWithCountdown, uid], function (err, data) {
            console.log('zadd complete', err, data);
            res.send('OK');
        });
    });
});

router.post('/getRange', function (req, res) {
    console.log('getRange req', req.body);
    let key = req.body.key;
    let start = req.body.start;
    let count = req.body.count;
    const args2 = [key, "+inf", "-inf", "WITHSCORES", "LIMIT", start, count];
    client.zrevrangebyscore(args2, function (rangeError, rangeResponse) {
        if (rangeError) throw rangeError;
        console.log("getRange response", rangeResponse.length);
        let rCount = rangeResponse.length / 2;
        let readyCount = 0;
        let result = [];
        if (rCount == 0) res.send(result);
        else {
            for (let i = 0; i < rCount; i++) {
                let uid = rangeResponse[i * 2];
                let score = Number(rangeResponse[i * 2 + 1]);
                let userkey = `user:${uid}`;
                let params = { uid, score, user: null };
                result.push(params);
                client.hgetall(userkey, function (err, data) {
                    if (err != null) {
                        console.log('err', err);
                    } else {
                        params.user = data;
                    }
                    readyCount++;
                    if (readyCount === rCount) {
                        res.send(result);
                    }
                });
            }
        }
    });
});

router.post('/getByUid', function (req, res) {
    let uid = req.body.uid;
    let userkey = `user:${uid}`;
    console.log('getByUid req', req.body, userkey);
    client.hgetall(userkey, function (err, data) {
        console.log('hgetall complete', err, userkey);
        res.send(data);
    })
});

router.post('/getRank', function (req, res) {
    let key = req.body.key;
    let uid = req.body.uid;
    client.zrevrank(key, uid, function (err, data) {
        console.log('zrevrank', err, data);
        res.send({ rank: data });
    });
});

module.exports = router;
